<?php

/**
 * 渠道申请控制器
 *
 * @author mengyuwang
 */

require_once 'CommonController.php';

class Admin_SourceController extends Admin_CommonController
{
    /**
     * 初始化函数
     * 
     * @return void
     */
    public function init()
    {
        parent::init();
        $this->_memberSourceApplymodel = new Application_Model_MemberSourceApply();
        $this->_productModel = new Application_Model_PartnerProduct();
        $this->_sourceModel = new Application_Model_Source();
        $this->_sourceAppModel = new Application_Model_SourceApp();
        $this->_partnerProductModel = new Application_Model_PartnerProduct();
        $this->_memberManagerModel = new Application_Model_MemberManager();
        $this->_memberModel = new Application_Model_Member();
        $this->view->title = "管理中心";
        $this->_roleModel = new Application_Model_Role();
        $this->_userRoleModel = new Application_Model_UserRole();
        $this->_userModel = new Application_Model_User();
        $this->username = Application_Model_UserLogin::getInstance()->getLoginedUserName();
    }

    /**
     * sourceid列表
     * @author wuhaifeng
     * @return void
     */
    public function listAction(){
        //获取当前页码
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $pageSize = 20;
        $pageNo = intval($this->_request->get('pageNo'));
        if (empty($pageNo)) {
            $pageNo = 1;
        }
        
        //设置URL模板
        $urls = array();
        $wheres = array();
        
        $memberName = trim($this->_request->get('memberName'));//关键字
        $this->view->memberName = $memberName;
        if (!empty($memberName)) {
            $urls['memberName'] = $memberName;
            $wheres[] = "m.name LIKE '%" . addslashes($memberName) . "%'";
        }
        
        $sourceId = trim($this->_request->get('sourceId'));//搜索类型
        $this->view->sourceId = $sourceId;
        if (!empty($sourceId)) {
            $urls['sourceId'] = $sourceId;
            $wheres[] = "s.sourceId LIKE '%" . addslashes($sourceId) . "%'";
        }
        
        $urls['pageNo'] = '{page}';
        $urlTemplate = $this->view->projectUrl($urls);

        //获取总页数以及记录
        $where = " WHERE p.code = '{$productCode}' ";
        $where .= count($wheres) > 0 ? ' AND ' . implode(' AND ', $wheres) . ' ' : '';
        $PartnerProductModel = new Application_Model_PartnerProduct();
        $MemberModel = new Application_Model_Member();
        $sql = "SELECT s.*,p.name AS productName,m.name AS memberName 
            FROM `{$this->_sourceModel->getTableName()}` AS s 
            LEFT JOIN `{$PartnerProductModel->getTableName()}` AS p ON s.productCode = p.code
            LEFT JOIN `{$MemberModel->getTableName()}` AS m ON s.memberCode = m.code
            {$where} 
            ORDER BY s.id
        ";
        $dbPaginator = new Application_Model_DbPaginator($sql, $pageSize, $pageNo);
        $recordCount = $dbPaginator->getRecodCount();
        //获取分页html字符
        Zend_Loader::loadClass('Project_Paginator');
            
        $paginator = new Project_Paginator($recordCount, $pageSize, $pageNo);
        $paginator->urlTemplateContent = $urlTemplate;
        //分配view(分页处理后的记录集以及分页HTML字符)
        $this->view->pageString = $paginator->getPageString();        
        $this->view->rows = $dbPaginator->getRows();
        $urls['pageNo'] = $pageNo;
        $this->view->pageUrl = $this->view->projectUrl($urls);
    }

    /**
    * 未知sourceid,sourcesubid列表
    * @author wuhaifeng
    * @return void
    */
    public function noMemberNameSourceListAction()
    {
        //获取当前页码
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        if ($this->_request->isPost() && $this->_request->get('in') == 1) {
            $memberTmp = array();
            $member = array();
            $memberSou = array();
            $memberSouSub = array();
            $memberTmp = $this->_request->getPost('member');
            $memberSou = $this->_request->getPost('memberSou');
            $memberSouSub = $this->_request->getPost('memberSouSub');
            $dataMem = array();
            $type = 0;
            foreach ($memberTmp as $item) {
                if(!empty($item)) {
                    $type = 1;
                }
                $member[] = trim($item);
            }
            if ($type == 0) {
                echo $this->view->message('无数据更新！', $this->view->projectUrl(array('action' => 'no-member-name-source-list'))) ;
                exit;
            }
            for ($i=0;$i<count($memberSou);$i++) {
                $dataMem[$i]['productCode'] = $productCode;
                $dataMem[$i]['sourceId'] = $memberSou[$i];
                $dataMem[$i]['sourceSubId'] = $memberSouSub[$i];
                $dataMem[$i]['name'] = $member[$i];
            }
            foreach ($dataMem as $key => $value) {
                if (empty($value['name'])) {
                    unset($dataMem[$key]);
                }
            }
            $nameArr = $this->_memberModel->fetchAll(" `name` in ('" . implode("','", $member) . "') ");
            
            foreach ($dataMem as $item) {
                $ii = 0;
                foreach ($nameArr as $kkk) {
                    if ($item['name'] == $kkk['name']) {
                        $item['memberCode'] = $kkk['code'];
                        $ii = 1;
                    }
                }
                if ($ii == 1) {
                    $data = array();
                    $data['productCode'] = $item['productCode'];
                    $data['sourceId'] = $item['sourceId'];
                    $data['sourceSubId'] = $item['sourceSubId'];
                    $fil = $this->_sourceModel->filterData($data);

                    if (!empty($fil)) {
                        $memarr = array();
                        $memarr['memberCode'] = $item['memberCode'];
                        $this->_sourceModel->update($memarr, " `productCode`='{$item['productCode']}' AND `sourceId`='{$item['sourceId']}' AND `sourceSubId`='{$item['sourceSubId']}' ");
                    } else {
                        $data = array();
                        $data['memberCode'] = $item['memberCode'];
                        $data['productCode'] = $item['productCode'];
                        $data['sourceId'] = $item['sourceId'];
                        $data['sourceSubId'] = $item['sourceSubId'];
                        $data['addTime'] = date('Y-m-d H:i:s');
                        $data['addUserName'] = $this->username;
                        $this->_sourceModel->insert($data);
                    }
                } else {
                    $memberData = array();
                    $updateMemberData = array();
                    $data = array();
                    $memberData['status'] = 1;
                    $memberData['name'] = $item['name'];
                    $memberData['addTime'] = date('Y-m-d H:i:s');
                    $memberData['addUserName'] = $this->username;
                    $id = $this->_memberModel->insert($memberData);
                    $updateMemberData['code'] = '10000'.$id;
                    $this->_memberModel->update($updateMemberData, " `id`='{$id}' ");
                    
                    $data = array();
                    $data['productCode'] = $item['productCode'];
                    $data['sourceId'] = $item['sourceId'];
                    $data['sourceSubId'] = $item['sourceSubId'];
                    $fil = $this->_sourceModel->filterData($data);
                    if (!empty($fil)) {
                        $memarr = array();
                        $memarr['memberCode'] = $updateMemberData['code'];
                        $this->_sourceModel->update($memarr, " `productCode`='{$item['productCode']}' AND `sourceId`='{$item['sourceId']}' AND `sourceSubId`='{$item['sourceSubId']}' ");
                    } else {
                        $data = array();
                        $data['memberCode'] = $updateMemberData['code'];
                        $data['productCode'] = $item['productCode'];
                        $data['sourceId'] = $item['sourceId'];
                        $data['sourceSubId'] = $item['sourceSubId'];
                        $data['addTime'] = date('Y-m-d H:i:s');
                        $data['addUserName'] = $this->username;
                        $this->_sourceModel->insert($data);
                    }
                }
            }
            echo $this->view->message('操作成功！', $this->view->projectUrl(array('action' => 'no-member-name-source-list'))) ;
            exit;
        }
        $pageSize = 20;
        $pageNo = intval($this->_request->get('pageNo'));
        if (empty($pageNo)) {
            $pageNo = 1;
        }
        
        //设置URL模板
        $urls = array();
        $wheres = array();
        
        $sourceId = trim($this->_request->get('sourceId'));
        $SourceSubId = trim($this->_request->get('SourceSubId'));
        if (!empty($sourceId)) {
            $urls['sourceId'] = $sourceId;
            $wheres[] = "aa.sourceId LIKE '%" . addslashes($sourceId) . "%'";
        }
        if (!empty($SourceSubId)) {
            $urls['sourceSubId'] = $SourceSubId;
            $wheres[] = "aa.sourceSubId LIKE '%" . addslashes($SourceSubId) . "%'";
        }
        $this->view->sourceId = $sourceId;
        $this->view->SourceSubId = $SourceSubId;
        $urls['pageNo'] = '{page}';
        $urlTemplate = $this->view->projectUrl($urls);
        //获取总页数以及记录
        $wheres[] = " aa.productCode = '{$productCode}' ";
        $where = '';
        $where .= count($wheres) > 0 ? ' AND ' . implode(' AND ', $wheres) . ' ' : '';
        $MemberModel = new Application_Model_Member();
        $SourceModel = new Application_Model_Source();
        $DayDataModel = new Application_Model_DayData();
        $sql = "SELECT  sourceId,sourceSubId,productCode,memberCode,name,num 
                FROM (
                    SELECT aa.sourceId,aa.sourceSubId,aa.productCode,b.memberCode,SUM(aa.okOrderNum) AS num,cc.name  
                    FROM mob_day_data AS aa 
                    LEFT JOIN mob_source AS b ON aa.sourceId=b.sourceId AND aa.sourceSubId=b.sourceSubId AND aa.productCode=b.productCode 
                    LEFT JOIN mob_member AS cc ON b.memberCode=cc.code 
                    WHERE cc.name IS NULL " . $where . " GROUP BY aa.sourceId,aa.sourceSubId  
                )ee   GROUP BY sourceId,sourceSubId
                ";
        $dbPaginator = new Application_Model_DbPaginator($sql, $pageSize, $pageNo);
        $recordCount = $dbPaginator->getRecodCount();
        //获取分页html字符
        Zend_Loader::loadClass('Project_Paginator');
            
        $paginator = new Project_Paginator($recordCount, $pageSize, $pageNo);
        $paginator->urlTemplateContent = $urlTemplate;
        //分配view(分页处理后的记录集以及分页HTML字符)
        $this->view->pageString = $paginator->getPageString();        
        $this->view->rows = $dbPaginator->getRows();
        $urls['pageNo'] = $pageNo;
        $this->view->pageUrl = $this->view->projectUrl($urls);
    }

    
    /**
    * sourceid列表
    * @author wuhaifeng
    * @return void
    */
    public function insertAction()
    {
        $memberMode = new Application_Model_Member();
        $this->view->allMember = $memberMode->fetchAll(NULL, $order = "CONVERT( `name` USING gbk )");
        if ($this->_request->isPost()) {
            $row = array();
            $filter = new Zend_Filter_StripTags();
            $memberCode = $filter->filter(trim($this->_request->getPost('memberCode')));
            $productCode = $filter->filter(trim($this->_request->getPost('productCode')));
            $addTime = date('Y-m-d H:i:s');
            $addUserName = $this->username;
            
            if ($memberMode->isExists($memberCode) == 0) {
                echo $this->view->message('渠道不存在，请重新填写！') ;
                exit;
            }
            $source = $filter->filter(trim($this->_request->getPost('sourceId')));
            $sourceReplace = str_replace("\r", "", $source);
            $sourceExplode = explode("\n", $sourceReplace);
            $sourceArray = array();
            foreach ($sourceExplode as $item) {
                $sourceArray = explode(",", $item);
                $row['memberCode'] = $memberCode;
                $row['productCode'] = $productCode;
                $row['sourceId'] = $sourceArray[0];
                $row['sourceSubId'] = empty($sourceArray[1]) ? $sourceArray[0] : $sourceArray[1];
                $row['addTime'] = $addTime;
                $row['addUserName'] = $addUserName;
                $this->_sourceModel->insert($row);
            }
            
            echo $this->view->message('操作成功！', $this->view->projectUrl(array('action' => 'list'))) ;
            exit;
        }      
        $this->view->productCode = $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $product = new Application_Model_PartnerProduct();
        $this->view->productName = $product->getProductNameByProductCode($productCode);
    }
    
    /**
     * 删除动作
     * 
     * @return void
     */
    public function deleteAction()
    {
        if ($this->_request->isPost()) {
            $ids= $this->_request->getPost('selectId');
            if (is_array($ids)) {
                $this->_sourceModel->deleteById($ids);
            }
        }
        $backUrl = urldecode($this->_request->get('backUrl'));
        redirect($backUrl);
    }
    
    /**
     * 导入列表
     * @return void
     */
    public function importAction()
    {
        if ($this->_request->isPost()) {
            if (!is_uploaded_file($_FILES['uploadfile']['tmp_name'])) {
                echo $this->view->message('上传错误！') ;
                exit;
            }
            if ($_FILES["uploadfile"]["size"] > 10000000) { //1M
                echo $this->view->message('上传文件不能大于1MB！') ;
                exit;
            }
            $ext = strtolower(substr($_FILES['uploadfile']['name'], strrpos($_FILES['uploadfile']['name'], '.') + 1));
            if (!($ext == 'xls' || $ext == 'xlsx')) {              
                echo $this->view->message('你只能上传XLS、XLSX格式文件！') ;
                exit;
            }
            $path = PUBLIC_PATH . "/data/memberTemp";
            createDirectory($path);
            $fileName = date("YmdHis") . ".{$ext}";
            copy($_FILES["uploadfile"]["tmp_name"] , $path . "/" . $fileName);
            echo "上传成功，正在准备导入..." . "<br><br>";
            $objPHPExcel = PHPExcel_IOFactory::load($path . "/{$fileName}");
            $objWorksheet = $objPHPExcel->getActiveSheet();
            $highestRow = $objWorksheet->getHighestRow();
            $successNum = 0;
            $updateNum = 0;
            $memberKey = 0;
            $time = time();
            $data = array();
            $tmpArray = array();

            $userLoginModel = Application_Model_UserLogin::getInstance();
            $currentProductCode = $userLoginModel->getUserCurrentProductCode();

            $memberModel = new Application_Model_Member();

            $memberTemp = array();

            $productModel = new Application_Model_PartnerProduct();
            for ($i = 2; $i <= $highestRow; $i++) {
                $n = $i - 1;
                $field = array();
                $field['memberName'] = trim($objWorksheet->getCellByColumnAndRow(0, $i)->getValue());
                $data['sourceId'] = trim($objWorksheet->getCellByColumnAndRow(1, $i)->getValue());
                $data['sourceSubId'] = trim($objWorksheet->getCellByColumnAndRow(2, $i)->getValue());
                $data['sourceName'] = trim($objWorksheet->getCellByColumnAndRow(3, $i)->getValue());
                $data['addTime'] = date('Y-m-d H:i:s',time());
                $data['addUserName'] = $this->username;

                if ($field['memberName'] == '') {
                    echo "第{$n}条，导入失败，渠道名称为空。<br/><br/>\r\n\r\n";
                } else if ($data['sourceId'] == '') {
                    echo "第{$n}条，导入失败，sourceId空。<br/><br/>\r\n\r\n";
                } else if ($data['sourceSubId'] == '') {
                    echo "第{$n}条，导入失败，sourceSubId为空。<br/><br/>\r\n\r\n";
                } else if ($data['sourceName'] == '') {
                    echo "第{$n}条，导入失败，sourceName为空。<br/><br/>\r\n\r\n";
                } else {
                    $memberKey = md5($field['memberName']);
                    if (!isset($memberTemp[$memberKey])) {
                        $memberCode = $memberModel->getCodeByMemberName($field['memberName']);

                        if (!$memberCode) {
                            $member['status'] = 1;
                            $member['name'] = $field['memberName'];
                            $member['addTime'] = date('Y-m-d H:i:s',time());
                            $member['addUserName'] = $this->username;
                            $memberId = $memberModel->insert($member);
                            $memberUpdate['code'] = "10000{$memberId}";
                            $memberModel->update($memberUpdate, "`id` = {$memberId}");
                            $memberCode = $memberUpdate['code'];
                        }
                        $memberTemp[$memberKey] = $memberCode;
                    }

                    $data['memberCode'] = $memberTemp[$memberKey];
                    $data['productCode'] = $currentProductCode;

                    if ($this->_sourceModel->isExists($data['productCode'], $data['sourceId'], $data['sourceSubId']) == 0) {
                        $this->_sourceModel->insert($data);
                        $successNum++;
                        echo "第{$n}条，SourceId“{$data['sourceId']}”导入成功。<br/><br/>\r\n\r\n";
                    } else {
                        $update = array();
                        $update['sourceName'] = $data['sourceName'];
                        $update['memberCode'] = $data['memberCode'];
                        $this->_sourceModel->update($update , " productCode = '{$data['productCode']}' AND sourceId = '{$data['sourceId']}' AND sourceSubId = '{$data['sourceSubId']}' ");
                        $updateNum++;
                        echo "第{$n}条，SourceId“{$data['sourceId']}”更新成功。<br/><br/>\r\n\r\n";
                    }
                }
            }
            unlink($path . "/" . $fileName);
            echo "共{$highestRow}条记录；成功导入{$successNum}条记录；成功更新{$updateNum}条记录<script>setTimeout(function(){location.href='{$this->view->projectUrl()}';}, 10000);</script>";
            exit;
        }
    }
    
    /**
     * 申请列表
     * 
     * @return void
     */
    public function index($wheres=array())
    {
        $this->view->products = $this->_productModel->fetchAll();
        
        
        //获取当前页码
        $pageSize = 20;
        $pageNo = intval($this->_request->get('pageNo'));
        if (empty($pageNo)) {
            $pageNo = 1;
        }
        
        //设置URL模板
        $urls = array();
        $memberCode = trim($this->_request->get('memberCode'));//渠道编号
        $this->view->memberCode = $memberCode;
        
        $productCode = trim($this->_request->get('productCode'));//产品编号
        $this->view->productCode = $productCode;
        
        $osName = trim($this->_request->get('osName'));//操作系统
        $this->view->osName = $osName;
        
        $status = intval($this->_request->get('status'));//审核状态
        $this->view->status = $status;

        if ($memberCode) {
            $urls['memberCode'] = $memberCode;
            $wheres[] = "`memberCode` LIKE '%" . addslashes($memberCode) . "%'";
        }
        
        if ($productCode) {
            $urls['productCode'] = $productCode;
            $wheres[] = "`productCode` LIKE '%" . addslashes($productCode). "%'";
        }
        
        if ($osName) {
            $urls['osName'] = $osName;
            $wheres[] = "`osName` LIKE '%" . addslashes($osName). "%'";
        }    

                
        if ($status) {
            $urls['status'] = $status;
            $wheres[] = "sa.`status` = {$status}";
        }
        
        
        $urls['pageNo'] = '{page}';
        $urlTemplate = $this->view->projectUrl($urls);
        //获取总页数以及记录
        $where = count($wheres) > 0 ? ' WHERE ' . implode(' AND ', $wheres) . ' ' : '';
        $sql = "SELECT sa.id as `id` ,sa.applyNum as `applyNum`, 
        m.name as `memberCode`,sa.osName as `osName`, 
        sa.applyUserName as `applyUserName` , 
        sa.applyTime as `applyTime`,sa.status as `status` ,
        pp.name as `productName` ,
        sa.productCode as `productCode`,
        sa.applyUserName as `applyUserName`,
        sa.applyNotes as `applyNotes`,
        sa.checkTime as `checkTime`
        FROM `{$this->_memberSourceApplymodel->getTableName()}` 
        as sa 
        left outer join `{$this->_partnerProductModel->getTableName()}` as pp 
        on sa.productCode like pp.code 
        left outer join `{$this->_memberModel->getTableName()}` as m
        on sa.memberCode = m.code
        {$where} ORDER BY sa.applyTime DESC";
        
        $dbPaginator = new Application_Model_DbPaginator($sql, $pageSize, $pageNo);
        $recordCount = $dbPaginator->getRecodCount();
        //获取分页html字符
        Zend_Loader::loadClass('Project_Paginator');
        $paginator = new Project_Paginator($recordCount, $pageSize, $pageNo);
        $paginator->urlTemplateContent = $urlTemplate;

        //分配view(分页处理后的记录集以及分页HTML字符)
        $this->view->pageString = $paginator->getPageString();
        $this->view->rows = $dbPaginator->getRows();
        $urls['pageNo'] = $pageNo;
        $this->view->pageUrl = $this->view->projectUrl($urls);

    }
    /**
     * 申请列表-管理员
     * 
     * @return void
     */
    public function indexAdminAction()
    {   
         $this->view->suffix="admin";
         $this->index();
    }
    /**
     * 申请列表 - 渠道经理
     * Enter description here ...
     */
    public function indexManagerAction()
    {          
        $this->view->suffix="manager";                
        $wheres[] = " sa.`applyUserName` = '{$this->_currentUserRow['userName']}' ";
        $this->index($wheres);                 
    }
   /**
    * 申请列表 - sid专员
    */
    public function indexSidAction()
    {
        $this->view->suffix="sid";                
        $wheres[] = " sa.`status`=2 or sa.`status`=1 ";
        $this->index($wheres);       
    }
   /**
    * 申请列表 - sid专员主管
    */
    public function indexSidAdminAction()
    {
        $this->view->suffix="sid-admin";                
        $wheres[] = " sa.`status` = 6 ";
        $this->index($wheres);       
    }
    /**
     * 申请列表 - 上传人员
     * Enter description here ...
     */
    public function indexUploadAction()
    {          
        $this->view->suffix="upload";                
        $wheres[] = " sa.`appUploadUserName` = '{$this->_currentUserRow['userName']}' ";
        $this->index($wheres);    
        
    }
    /**
     * 申请列表 - 测试人员
     * Enter description here ...
     */
    public function indexTestAction()
    {   
        $this->view->suffix = "test";               
        $wheres[] = " sa.`appTestUserName` = '{$this->_currentUserRow['userName']}' ";                
        $this->index($wheres);      
    }

    /**
     * 渠道申请详情
     * @return void
     */
    public function detail()
    {
        $id = intval($this->_request->get('id'));
        $this->view->row = $this->_memberSourceApplymodel->getDetailById($id);
        $this->view->sourceId = $this->_sourceAppModel->getSourceId($id);
        $this->view->sourceSubIds = $this->_sourceAppModel->getSourceSubIds($id);
    }
    
    /**
     * 渠道申请详情 - 管理员
     */
    public function detailAdminAction()
    {
        $this->view->suffix="admin";
        $this->detail();
        $this->renderScript('source/detail.php');
    }
    /**
     * 渠道申请详情 - 渠道经理
     */
    public function detailManagerAction()
    {
        $this->view->suffix="manager";
        $this->detail();
        $this->renderScript('source/detail.php');
    }
    
    /**
     * 渠道申请详情 - 上传人员
     */
    public function detailUploadAction()
    {
        $this->view->suffix="upload";
        $this->detail();
        $this->renderScript('source/detail.php');
    }
    
    
    /**
     * 渠道申请详情 - 测试人员
     */
    public function detailTestAction()
    {
        $this->view->suffix="test";
        $this->detail();
        $this->renderScript('source/detail.php');
    }
    /**
     * 渠道经理申请
     * 
     * @return void
     */
    public function apply()
    {
        $this->view->memberCode = $this->_request->get('memberCode');
        $this->view->products = $this->_productModel->fetchAll();
        $osNames = $this->_request->getPost('cbOsName');
        $applyNums = $this->_request->getPost('applyNum');
        $filter = new Zend_Filter_StripTags();

        if ($this->_request->isPost()) {
            
           if(count($osNames)==0) {
            //没有填写操作系统信息
              echo $this->view->message('请勾选操作系统和软件包数量，请重新填写！') ;
            exit;
           }
            for ($j=0;$j<count($osNames);++$j) {
                    $row = array();
                    $row['memberCode'] = $filter->filter(trim($this->_request->getPost('memberCode')));
                    $row['productCode'] = $filter->filter(trim($this->_request->getPost('productCode')));
                    $row['osName'] = $filter->filter(trim($osNames[$j]));
                    $row['applyNum'] = intval($applyNums[$row['osName']]);
                    $row['applyTime'] = date('Y-m-d H:i:s');
                    $row['applyUserName'] = $this->_currentUserRow['userName'];
                    $row['applyNotes'] = trim($filter->filter(trim($this->_request->getPost('applyNotes'))));
                    $row['status'] = 1;           
                    if ($row['memberCode']=='') {
                        echo $this->view->message('没有渠道编号，请重新填写！') ;
                        exit;
                    }
                    if ($row['productCode']=='') {
                    echo $this->view->message('必须选择产品，请重新填写！') ;
                    exit;
                    }
                    if($row['applyNum']<=0) {
                            echo $this->view->message('软件包数量必须大于0，请重新填写！') ;
                            exit;
                        
                    }

                //插入到渠道申请安装包主表
                $memberSourceApplyId = $this->_memberSourceApplymodel->insert($row);
                
                
                 $row_source=array(
	                'memberCode'=>$row['memberCode'],
	                'productCode'=>$row['productCode'],
	                'sourceId'=>$this->_sourceModel->createSourceId($row['memberCode'],$row['productCode']),
	                'sourceSubId'=>'',
	                'notes'=>'',
	                'addTime'=>date('Y-m-d H:i:s'),
	                'addUserName'=>Application_Model_UserLogin::getInstance()->getLoginedUserName()
	                );
	                
                //插入到渠道申请安装包从表mob_source_app            
                for($i=1; $i<=$row['applyNum'];++$i) {
                    $row_source_app=array();
                    $row_source_app['productCode']=$row['productCode'];
                    $row_source_app['osName']=$row['osName'];
                    $row_source_app['sourceId']=$row_source['sourceId'];
                    $row_source_app['sourceSubId']='';
                    $row_source_app['memberCode']=$row_source['memberCode'];
                    $row_source_app['path']='';
                    $row_source_app['addTime']=date('Y-m-d H:i:s');
                    $row_source_app['uploadUserName']='';
                    $row_source_app['status']=1;
                    $row_source_app['memberSourceApplyId']= $memberSourceApplyId;
                    $id=$this->_sourceAppModel->insertRow($row_source_app);
                    $row_source_app=$this->_sourceAppModel->fetchRow("id={$id}");
                    
                    
                    $row_source_ins=array(
	                'memberCode'=>$row['memberCode'],
	                'productCode'=>$row['productCode'],
	                'sourceId'=>$this->_sourceModel->createSourceId($row['memberCode'],$row['productCode']),
	                'sourceSubId'=>$row_source_app['sourceSubId'],
	                'notes'=>'',
	                'addTime'=>date('Y-m-d H:i:s'),
	                'addUserName'=>Application_Model_UserLogin::getInstance()->getLoginedUserName()
	                );
	                $this->_sourceModel->insert($row_source_ins);
                    

                }
                
                
            }
            
            //返回结果
            $msg='';
            $msg .= '操作成功！申请的SOURCEID为：'.$row_source['sourceId'].'<br />';
            echo $this->view->message($msg, $this->view->projectUrl(array('action' => 'index-'.$this->view->suffix))) ;
            exit;
            }
        $this->renderScript('source/apply.php');
        }    
  
    /**
     * 渠道申请 - 管理员
     */
    public function applyAdminAction()
    {
        $this->view->suffix="admin";
        $this->apply();
    }
     /**
     * 渠道申请 - 渠道经理
     */
    public function applyManagerAction()
    {
        $this->view->suffix="manager";
        $this->apply();
    }
    
    
    /**
     * 获取产品编号获取关联的系统名
     * @return json string
     */
    public function osnamesAction() 
    {
        $productCode= trim($this->_request->getPost('productCode'));
        $row = $this->_memberSourceApplymodel->getOsNamesByProductCode($productCode);
        $json_string=json_encode($row);
        echo $json_string;
        exit();
        
    }
    /**
     * 从角色编号 获取 用户名
     */
    public function getUserNamesByRoleIdAction()
    {
        $roleId = intval($this->_request->getPost('roleId'));
        $row = $this->_userRoleModel->getUserNamesByRoleId($roleId);
        $json_string = json_encode($row);
        echo $json_string;
        exit();
        
    }

    /**
     * 更新操作 - 管理员
     */
    public function updateAdminAction()
    {
        $this->view->suffix='admin';
        $this->update();
    }
    
    /**
     * 更新操作 - 渠道经理
     */
    public function updateManagerAction()
    {
        $this->view->suffix='manager';
        $this->update();
    }
    /**
     * 更新动作
     * 
     * @return void
     */
    public function update()
    {
        $id = intval($this->_request->get('id'));
        if (empty($id)) {
             throw new Exception('Invalid params!');
        }
        $this->view->row = $this->_memberSourceApplymodel->fetchRow("`id` = {$id}"); 
       
        $backUrl = urldecode($this->_request->get('backUrl'));
        if ($this->_request->isPost()) {
             $row = array();
            $filter = new Zend_Filter_StripTags();
            $row['applyNum'] = intval($filter->filter(trim($this->_request->getPost('applyNum'))));
            $row['applyNotes'] = trim($filter->filter(trim($this->_request->getPost('applyNotes'))));

            if (strlen($row['applyNum']) <=0 ) {
                echo $this->view->message('软件包数量必须大于0，请重新填写！') ;
                exit;
            }
           
            $this->_memberSourceApplymodel->update($row, "`id` = {$id}");
            
            $row_app['memberSourceApplyId']=$this->view->row['id'];
            $row_app['memberCode']=$this->view->row['memberCode'];
            $row_app['osName']=$this->view->row['osName'];
            $row_app['productCode']=$this->view->row['productCode'];
            $row_app['applyNum']=$row['applyNum'];
            $row_app['sourceId']=$this->_sourceModel->getSourceIdByMemberCodeProductCode($row_app);

            
           
            $this->_sourceAppModel->updateReloation($row_app);
            
            
            echo $this->view->message('操作成功！', $backUrl) ;
            exit;
        }
        
    }
    /**
     * 管理员更新审核状态
     */
    public function updateStatusAdminAction()
    {
        $this->view->suffix="admin";
        $this->updateStatus();
    }
    
    /**
     * SID专员更新审核状态
     */
    public function updateStatusSidAction()
    {
        $this->view->suffix="sid";
        $this->updateStatus();
    }
    
    /**
     * SID专员主管更新审核状态
     */
    public function updateStatusSidAdminAction()
    {
        $this->view->suffix="sid-admin";
        $this->updateStatus();
    }
    
    

    /**
     * 修改申请状态
     * Enter description here ...
     * @throws Exception
     */
    public function updateStatus()
    {
      $id = intval($this->_request->get('id'));
        if (empty($id)) {
             throw new Exception('Invalid params!');
        }
        $filter = new Zend_Filter_StripTags();
        //$this->view->row = $this->_memberSourceApplymodel->fetchRow("`id` = {$id}"); 
        $this->view->row = $this->_memberSourceApplymodel->getDetailById($id);
        $this->view->sourceId = $this->_sourceAppModel->getSourceId($id);
        $this->view->sourceSubIds = $this->_sourceAppModel->getSourceSubIds($id);
        $this->view->roles = $this->_roleModel->fetchAll("`type`='1'");
        $backUrl = $this->view->projectUrl(array('action'=>'update-status-'.$this->view->suffix,'id'=>$id));
        if ($this->_request->isPost()) {
             $row = array();          
            $row['status'] = intval($filter->filter(trim($this->_request->getPost('status')))); 
            $row['checkNotes'] = $filter->filter(trim($this->_request->getPost('checkNotes')));        
            $row['checkTime'] = date('Y-m-d H:i:s');
            $row['checkUserName'] = $this->_currentUserRow['userName'];
             //将状态位修改为已审核待打包(status=3)，同时发邮件，通知对应的操作系统平台打包人员 
                                  
             if($row['status']=="3") {
                 
                  $row['appUploadUserName'] = $filter->filter(trim($this->_request->getPost('appUploadUserName')));
                $row['appTestUserName'] = $filter->filter(trim($this->_request->getPost('appTestUserName')));
                if(empty($row['appUploadUserName']) || !$this->_userModel->isExists($row['appUploadUserName'])) {
                     echo $this->view->message('请选择有效上传管理员，请重新填写。') ;
                     exit;
                }
                 if(empty($row['appTestUserName']) || !$this->_userModel->isExists($row['appTestUserName'])) {
                     echo $this->view->message('请选择有效测试管理员，请重新填写。') ;
                     exit;
                }
             
                  //更新表mob_source_app
                $this->_sourceAppModel->update(
                array('testUserName'=>$row['appTestUserName'],'uploadUserName'=>$row['appUploadUserName']),
                "memberSourceApplyId = {$id}");    
                
             }
             

         //检测是否状态要切成6软件数量大于阀值
          $rowNew = $this->_memberSourceApplymodel->fetchRow("id={$id}");
            if($row['status']=="6") {
                if($rowNew['applyNum']<=$this->_configs['project']['softwareCheckNum']) {
                    echo $this->view->message('审核失败！软件包数量必须大于'.$this->_configs['project']['softwareCheckNum'].'。', $backUrl) ;
                    exit;
                }
            }
             
             //修改主表
            $this->_memberSourceApplymodel->update($row, "`id` = {$id}");
            
            //新的记录
              $rowNew = $this->_memberSourceApplymodel->fetchRow("id={$id}");
            
           
            
            
            //发送邮件
            if($row['status']=="3") {
    
                 $to = $this->_memberSourceApplymodel->getUploadAdminList($id);   
                 if(!$to) {
                      echo $this->view->message('邮件发送失败！请查看相关用户是否填写邮件地址。', $backUrl) ;
                    exit;
                 }else {
                     
                     $productName = $this->_productModel->getProductNameByProductCode($rowNew['productCode']);
                     $subject = $productName."Source软件包打包申请自动提醒";
                    //$link_url=$this->_configs['project']['hostUrl'].$this->view->projectUrl(array('action'=>'app-list','memberSourceApplyId'=>$this->view->row['id']));                            
                    //获取申请人名字
                     $applyUser = $this->_userModel->getNameByUserName($rowNew['applyUserName']);
                     //获取审核时间
                    $checkTime = $rowNew['checkTime'];
                    //获取审核管理员名字
                    $checkUser = $this->_userModel->getNameByUserName($rowNew['checkUserName']);
                    
                        $message = "
                        <html>
                        <head>
                        <title>".$subject."</title>
                        </head>
                        <body>
                        <p>你好</p>
                        
                        <p>".$applyUser."提交了一个乐峰打包申请，并且在".$checkTime."通过".$checkUser."的审核。</p>
                        
                        <p>请登录系统查看具体的申请sourceId和sourceSubId列表，并打包上传至服务器。</p>
                        
                        <p>注：以上邮件为系统自动发送，请勿回复，如有疑问请与".$checkUser."联系。</p>
                        
                        </body>
                        </html>
                        ";
                    
                    
                    $mailModel = new Application_Model_Mail();
                    $mailModel->sendMul($to, $subject, $message);
                    
                    if ($mailModel->getSendStaus() != 0) {
                        echo $mailModel->getSendInfo();
                        exit();
                        
                        echo $this->view->message('发送失败！<br/>错误如下：' . $mailModel->getSendInfo()) ;
                        exit;
                    } else {
                       ;
                    }
                     
                 }                      
                
            }
            $backUrl = $this->view->projectUrl(array('action'=>'index-'.$this->view->suffix));
            echo $this->view->message('操作成功！', $backUrl) ;
            exit;
        }
    }
    /**
     * 删除动作
     * 
     * @return void
     */
    public function deleteLinkAction()
    {
        $suffix = $this->_request->get('suffix');
        if ($this->_request->isPost()) {
            $ids= $this->_request->getPost('selectId');                        
            if (is_array($ids)) {
                foreach($ids as $id) {                    
                   //删除关联的sourceApp表里的内容
                    $this->_sourceAppModel->deleteRelationApp($id);
                    $this->_memberSourceApplymodel->delete("`id`={$id}");
                }
            }
        }
        $backUrl = urldecode($this->view->projectUrl(array('action'=>'index-'.$suffix)));
        redirect($backUrl);
    }
    

    
    
}